﻿using System;
using System.ComponentModel;
using System.Threading;
using Caliburn.PresentationFramework.RoutedMessaging;
using Exec = Caliburn.PresentationFramework.Invocation.Execute;

namespace MTGenome.Framework
{
    public class AsyncResult<T> : IResult
    {
        private readonly Func<T> _function;

        public AsyncResult(Func<T> function)
        {
            _function = function;
        }

        public T Result { get; set; }

        public void Execute(ResultExecutionContext context)
        {
            Exception exception = null;

            Exec.OnBackgroundThread(delegate
            {
                try
                {
                    Result = _function();
                }
                catch (Exception exc)
                {
                    exception = exc;
                }
            }, 
            (RunWorkerCompletedEventHandler)delegate
            {
                Completed(this, new ResultCompletionEventArgs { Error = exception });
            });
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }

    public class AsyncResult : IResult
    {
        private readonly Action _function;

        public AsyncResult(Action function)
        {
            _function = function;
        }

        public void Execute(ResultExecutionContext context)
        {
            Exception exception = null;

            Exec.OnBackgroundThread(delegate
            {
                try
                {
                    _function();
                }
                catch (Exception exc)
                {
                    exception = exc;
                }
            },
            (RunWorkerCompletedEventHandler)delegate
            {
                Completed(this, new ResultCompletionEventArgs { Error = exception });
            });
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}